/**
 * Copyright(c)2012 Beijing PeaceMap Co.,Ltd.
 * All right reserved. 
 */
package com.pmc.dwa.security.handler;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.session.SessionAuthenticationException;
import org.springframework.util.StringUtils;

import com.pmc.dwa.common.exception.PmcAccessDeniedException;
import com.pmc.dwa.common.exception.PmcRuntimeException;
import com.pmc.dwa.common.utils.Escape;
import com.pmc.dwa.common.utils.Httptear;
import com.pmc.dwa.security.service.IUserService;
import com.pmc.dwa.security.utils.PmcAttributes;

/**
 * @description 登录失败处理
 * @author aokunsang
 * @date 2013-1-6
 */
public class LoginAuthenticationFailureHandler implements
		AuthenticationFailureHandler {
	
	protected final Log logger = LogFactory.getLog(getClass());
	
	private String defaultUrl;
	private String modesymbol;   //登录类型标示符
	private IUserService userService;
	private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
	 
	@Override
	public void onAuthenticationFailure(HttpServletRequest request,
			HttpServletResponse response, AuthenticationException ex)
			throws IOException, ServletException {
		String login_mode = request.getParameter(modesymbol);   //获取登录模式
		String redirect_url = "";
		userService.addSyslog(request, "AuthenticationFailureHandler", "UnSuccAuth", ex.getMessage());
		if(StringUtils.hasText(login_mode) && PmcAttributes.PMC_LOGIN_MODE.equalsIgnoreCase(login_mode)){
			Httptear.ResponseResultByUTF8("{\"success\":false,\"msg\":\""+Escape.escape(ex.getMessage())+"\"}", response);
			return;
		}
		if(ex.getCause() instanceof PmcRuntimeException){  //如果是自定义异常，继续抛出到500页面展示
			throw ex;
		}else if(ex.getCause() instanceof PmcAccessDeniedException){ //用户暂无登录系统的权限
			redirect_url = defaultUrl + PmcAttributes.PMC_LOGIN_ACCESSDENIED_ERROR_CODE;
		}else if(ex.getClass() == SessionAuthenticationException.class){ //session超出最大值(maximumSessions)异常
			redirect_url = defaultUrl + PmcAttributes.PMC_LOGIN_SESSION_EXCEEDED_ERROR_CODE;
		}else{
			redirect_url = defaultUrl + PmcAttributes.PMC_LOGIN_ERROR_CODE;
		}
		System.out.println("[com.pmc.dwa.security.handler.LoginAuthenticationFailureHandler]User login failed！错误信息："+ex.getMessage());
        if (!StringUtils.hasText(defaultUrl)) {  //默认跳转的地方
            logger.warn("No failure URL set, sending 401 Unauthorized error");
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Authentication Failed: " + ex.getMessage());  
        }else{
        	redirectStrategy.sendRedirect(request, response, redirect_url);
        }
	}

	/**
	 * @param defaultUrl the defaultUrl to set
	 */
	public void setDefaultUrl(String defaultUrl) {
		this.defaultUrl = defaultUrl;
	}

	/**
	 * @param userService the userService to set
	 */
	public void setUserService(IUserService userService) {
		this.userService = userService;
	}

	/**
	 * @param modesymbol the modesymbol to set
	 */
	public void setModesymbol(String modesymbol) {
		this.modesymbol = modesymbol;
	}
}
